<template>
  <div class="version-statistics">
    <el-row :gutter="16">
      <!-- 基础统计卡片 -->
      <el-col :span="6" v-for="stat in basicStats" :key="stat.key">
        <el-card class="stat-card" :class="`stat-${stat.key}`">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="24">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
          <div v-if="stat.trend" class="stat-trend" :class="stat.trend.type">
            <el-icon :size="12">
              <ArrowUp v-if="stat.trend.type === 'up'" />
              <ArrowDown v-if="stat.trend.type === 'down'" />
              <Minus v-if="stat.trend.type === 'stable'" />
            </el-icon>
            <span>{{ stat.trend.value }}%</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 进度分布图表 -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>版本状态分布</span>
              <el-button type="text" @click="refreshStatusChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="statusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>发布状态分布</span>
              <el-button type="text" @click="refreshReleaseChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="releaseChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>版本发布趋势</span>
              <div class="header-actions">
                <el-radio-group v-model="trendPeriod" size="small" @change="refreshTrendChart">
                  <el-radio-button label="7d">7天</el-radio-button>
                  <el-radio-button label="30d">30天</el-radio-button>
                  <el-radio-button label="90d">90天</el-radio-button>
                </el-radio-group>
                <el-button type="text" @click="refreshTrendChart">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container trend-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { 
  FolderOpened, 
  Document, 
  WarningFilled, 
  SuccessFilled,
  ArrowUp,
  ArrowDown,
  Minus,
  Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import type { VersionStatistics as VersionStatsType } from '@/api/version'
import { useVersionStates } from '@/composables/useVersionStates'

// 从状态管理系统动态获取版本状态
const { versionStates } = useVersionStates()

interface StatTrend {
  type: 'up' | 'down' | 'stable'
  value: number
}

interface StatItem {
  key: string
  label: string
  value: number
  icon: any
  trend: StatTrend | null
}

interface Props {
  statistics: VersionStatsType
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// 图表引用
const statusChartRef = ref<HTMLElement>()
const releaseChartRef = ref<HTMLElement>()
const trendChartRef = ref<HTMLElement>()

// 图表实例
let statusChart: echarts.ECharts | null = null
let releaseChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// 趋势周期
const trendPeriod = ref('30d')

// 基础统计数据
const basicStats = ref<StatItem[]>([
  {
    key: 'total',
    label: '总版本数',
    value: 0,
    icon: FolderOpened,
    trend: null
  },
  {
    key: 'tasks',
    label: '关联任务',
    value: 0,
    icon: Document,
    trend: null
  },
  {
    key: 'defects',
    label: '关联缺陷',
    value: 0,
    icon: WarningFilled,
    trend: null
  },
  {
    key: 'released',
    label: '已发布',
    value: 0,
    icon: SuccessFilled,
    trend: null
  }
])

// 动态更新"已发布"标签
watch(() => versionStates.value, () => {
  const releasedState = versionStates.value.find(state => 
    state.name && (state.name.includes('已发布') || state.name.includes('发布'))
  )
  if (releasedState) {
    basicStats.value[3].label = releasedState.name
  }
}, { immediate: true })

// 初始化状态分布图表
const initStatusChart = () => {
  if (!statusChartRef.value) return
  
  statusChart = echarts.init(statusChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['规划中', '开发中', '测试中', '准备就绪', '已发布', '已归档']
    },
    series: [
      {
        name: '版本状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 0, name: '规划中', itemStyle: { color: '#909399' } },
          { value: 0, name: '开发中', itemStyle: { color: '#e6a23c' } },
          { value: 0, name: '测试中', itemStyle: { color: '#409eff' } },
          { value: 0, name: '准备就绪', itemStyle: { color: '#67c23a' } },
          { value: 0, name: '已发布', itemStyle: { color: '#67c23a' } },
          { value: 0, name: '已归档', itemStyle: { color: '#c0c4cc' } }
        ]
      }
    ]
  }
  
  statusChart.setOption(option)
}

// 初始化发布状态图表
const initReleaseChart = () => {
  if (!releaseChartRef.value) return
  
  releaseChart = echarts.init(releaseChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['未发布', '发布中', '已发布', '已回滚']
    },
    series: [
      {
        name: '发布状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 0, name: '未发布', itemStyle: { color: '#909399' } },
          { value: 0, name: '发布中', itemStyle: { color: '#e6a23c' } },
          { value: 0, name: '已发布', itemStyle: { color: '#67c23a' } },
          { value: 0, name: '已回滚', itemStyle: { color: '#f56c6c' } }
        ]
      }
    ]
  }
  
  releaseChart.setOption(option)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['创建版本', '发布版本']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '创建版本',
        type: 'line',
        stack: 'Total',
        data: [],
        itemStyle: { color: '#409eff' }
      },
      {
        name: '发布版本',
        type: 'line',
        stack: 'Total',
        data: [],
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 更新统计数据
const updateStatistics = () => {
  if (!props.statistics) return
  
  const stats = props.statistics as any
  
  // 更新基础统计
  basicStats.value[0].value = stats.total_versions || 0
  basicStats.value[1].value = stats.total_tasks || 0
  basicStats.value[2].value = stats.total_defects || 0
  
  // 动态查找"已发布"状态的代码，从 status_distribution 中获取数量
  const releasedState = versionStates.value.find(state => 
    state.name && (state.name.includes('已发布') || state.name.includes('发布'))
  )
  if (releasedState && stats.status_distribution) {
    basicStats.value[3].value = stats.status_distribution[releasedState.code] || 0
  } else {
    basicStats.value[3].value = stats.released_versions || 0
  }
  
  // 更新状态分布图表 - 动态从状态管理系统获取状态名称
  if (statusChart && stats.status_distribution) {
    const statusData: Array<{ value: number; name: string; itemStyle: { color: string } }> = []
    
    // 遍历状态管理系统中的所有状态
    versionStates.value.forEach(state => {
      const count = stats.status_distribution[state.code] || 0
      if (count > 0 || state.is_enabled !== false) {
        statusData.push({
          value: count,
          name: state.name || state.code,
          itemStyle: { color: state.color || '#909399' }
        })
      }
    })
    
    statusChart.setOption({
      series: [{
        data: statusData
      }]
    })
  }
  
  // 更新发布状态图表
  if (releaseChart && stats.release_distribution) {
    const releaseData = [
      { value: stats.release_distribution.unreleased || 0, name: '未发布' },
      { value: stats.release_distribution.releasing || 0, name: '发布中' },
      { value: stats.release_distribution.released || 0, name: '已发布' },
      { value: stats.release_distribution.rolled_back || 0, name: '已回滚' }
    ]
    
    releaseChart.setOption({
      series: [{
        data: releaseData
      }]
    })
  }
}

// 刷新图表
const refreshStatusChart = () => {
  statusChart?.resize()
}

const refreshReleaseChart = () => {
  releaseChart?.resize()
}

const refreshTrendChart = () => {
  trendChart?.resize()
}

// 组件挂载
onMounted(async () => {
  await nextTick()
  initStatusChart()
  initReleaseChart()
  initTrendChart()
  updateStatistics()
})

// 监听统计数据变化
watch(() => props.statistics, updateStatistics, { deep: true })

// 窗口大小变化时重新调整图表
window.addEventListener('resize', () => {
  statusChart?.resize()
  releaseChart?.resize()
  trendChart?.resize()
})
</script>

<style scoped>
.version-statistics {
  width: 100%;
}

.stat-card {
  margin-bottom: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-total .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-tasks .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-defects .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-released .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  margin-top: 8px;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

.stat-trend.stable {
  color: #909399;
}

.chart-row {
  margin-top: 16px;
}

.chart-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.trend-chart {
  height: 400px;
}
</style>